/*
 * ========================================================
 * Copyright(c) 2014 杭州偶尔科技-版权所有
 * ========================================================
 * 本软件由杭州偶尔科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * 
 * 			http://www.kkkd.com/
 * 
 * ========================================================
 */
package com.simon.mengkou.utils;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;

import com.facebook.common.references.CloseableReference;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeController;
import com.facebook.drawee.drawable.ScalingUtils.ScaleType;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.generic.RoundingParams;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.bitmaps.PlatformBitmapFactory;
import com.facebook.imagepipeline.request.BasePostprocessor;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.facebook.imagepipeline.request.Postprocessor;
import com.ouertech.android.agm.lib.base.constant.CstScheme;
import com.ouertech.android.agm.lib.base.utils.UtilDevice;
import com.ouertech.android.agm.lib.base.utils.UtilString;
import com.simon.mengkou.R;
import com.simon.mengkou.system.constant.CstOuer;

/**
 * @author : Zhenshui.Xia
 * @date : 2015/10/16.
 * @desc : 图片加载工具类
 */
public class UtilImage {
    private static UtilImage mInstance;
    private GenericDraweeHierarchyBuilder mDefaultHierarchyBuilder;
    private GenericDraweeHierarchyBuilder mRoundedHierarchyBuilder;
    private GenericDraweeHierarchyBuilder mCircleHierarchyBuilder;
    private GenericDraweeHierarchyBuilder mAvatarHierarchyBuilder;

    private Postprocessor mSkewXPostprocessor;

    private UtilImage(Context ctx) {
        //fresco初始化
        Fresco.initialize(ctx);

        Resources res = ctx.getResources();

        //默认图片配置
        BitmapDrawable defaultPlaceholderDrawable = new BitmapDrawable(res,
                BitmapFactory.decodeResource(res, R.drawable.common_ic_image_default));
        mDefaultHierarchyBuilder = new GenericDraweeHierarchyBuilder(res)
                .setFadeDuration(300)
                .setActualImageScaleType(ScaleType.FIT_XY)
                .setPlaceholderImage(defaultPlaceholderDrawable);

        //圆角图片配置
        float radius = UtilDevice.dip2px(ctx, 8);
        RoundingParams roundedParams = new RoundingParams();
        roundedParams.setRoundAsCircle(false);
        roundedParams.setCornersRadii(radius, radius, radius, radius);
        BitmapDrawable roundedPlaceholderDrawable = new BitmapDrawable(res,
                BitmapFactory.decodeResource(res, R.drawable.common_ic_launcher));
        mRoundedHierarchyBuilder = new GenericDraweeHierarchyBuilder(res)
                .setFadeDuration(300)
                .setActualImageScaleType(ScaleType.CENTER_CROP)
                .setPlaceholderImage(roundedPlaceholderDrawable, ScaleType.CENTER_CROP)
                .setRoundingParams(roundedParams);

        //圆形图片配置
        RoundingParams circleParams = new RoundingParams();
        circleParams.setRoundAsCircle(true);
        BitmapDrawable circlePlaceholderDrawable = new BitmapDrawable(res,
                BitmapFactory.decodeResource(res, R.drawable.common_ic_launcher));
        mCircleHierarchyBuilder = new GenericDraweeHierarchyBuilder(res)
                .setFadeDuration(300)
                .setActualImageScaleType(ScaleType.CENTER_CROP)
//                .setPlaceholderImage(circlePlaceholderDrawable, ScaleType.CENTER_CROP)
                .setRoundingParams(circleParams);

        //圆形图片配置
        RoundingParams avatarParams = new RoundingParams();
        avatarParams.setRoundAsCircle(true);
        BitmapDrawable avatarPlaceholderDrawable = new BitmapDrawable(res,
                BitmapFactory.decodeResource(res, R.drawable.user_ic_default_avatar));
        mAvatarHierarchyBuilder = new GenericDraweeHierarchyBuilder(res)
                .setFadeDuration(300)
                .setBackground(avatarPlaceholderDrawable)
                .setActualImageScaleType(ScaleType.CENTER_CROP)
                .setPlaceholderImage(avatarPlaceholderDrawable, ScaleType.CENTER_CROP)
                .setFailureImage(avatarPlaceholderDrawable, ScaleType.CENTER_CROP)
                .setRoundingParams(circleParams);



        mSkewXPostprocessor = new BasePostprocessor() {
            @Override
            public String getName() {
                return "SkewXPostprocessor";
            }

            @Override
            public CloseableReference<Bitmap> process(
                    Bitmap sourceBitmap,
                    PlatformBitmapFactory bitmapFactory) {
                int w = sourceBitmap.getWidth();
                int h = sourceBitmap.getHeight();
                int wh = w > h ? h : w;
                int retX = w > h ? (w - h) / 2 : 0;
                int retY = w > h ? 0 : (h - w) / 2;

                sourceBitmap = Bitmap.createBitmap(sourceBitmap, retX, retY, wh, wh, null, false);


                double value = 0.28;
                int skewX = (int) (wh * value);

                CloseableReference<Bitmap> bitmapRef = bitmapFactory.createBitmap(
                        wh + skewX, wh);
                try {

                    Bitmap destBitmap = bitmapRef.get();
                    destBitmap.setHasAlpha(true);
                    for (int y = 0; y < wh; y += 1) {
                        for (int x = 0; x < wh; x += 1) {
                            destBitmap.setPixel((int) (x + skewX - y *value), y, sourceBitmap.getPixel(x, y));
                        }
                    }

                    return CloseableReference.cloneOrNull(bitmapRef);
                } finally {
                    CloseableReference.closeSafely(bitmapRef);
                }
            }

        };
    }


    /**
     * 单例模式
     *
     * @param ctx 上下文
     * @return
     */
    public synchronized static UtilImage getInstance(Context ctx) {
        if (null == mInstance) {
            mInstance = new UtilImage(ctx);
        }

        return mInstance;
    }


    /**
     * 加载圆形头像
     * @param view
     * @param url
     */
    public void loadAvatar(SimpleDraweeView view, String url) {
        if(view != null) {
            view.setHierarchy(mAvatarHierarchyBuilder.build());
            Uri uri = UtilString.isNotBlank(url) ? Uri.parse(url)
                    : Uri.parse("res://com.simon.mengkou/" + R.drawable.user_ic_default_avatar);
            view.setImageURI(uri);
        }
    }


    /**
     * 加载图片
     * @param view
     * @param url
     */
    public void loadImage(SimpleDraweeView view, String url) {
        if(view != null && UtilString.isNotBlank(url)) {
            view.setHierarchy(mDefaultHierarchyBuilder.build());
            Uri uri = Uri.parse(url);
            view.setImageURI(uri);
        }
    }

    /**
     * 加载图片
     * @param view
     * @param url
     */
    public void loadImage(SimpleDraweeView view, String url, GenericDraweeHierarchyBuilder builder) {
        if(view != null && UtilString.isNotBlank(url)) {
            if(builder != null) {
                view.setHierarchy(builder.build());
            }

            Uri uri = Uri.parse(url);
            view.setImageURI(uri);
        }
    }

    /**
     * 加载带圆角的图片
     * @param view
     * @param url
     */
    public void loadRoundedImage(SimpleDraweeView view, String url) {
        if(view != null && UtilString.isNotBlank(url)) {
            view.setHierarchy(mRoundedHierarchyBuilder.build());
            Uri uri = Uri.parse(url);
            view.setImageURI(uri);
        }
    }

    /**
     * 加载圆形图片
     * @param view
     * @param url
     */
    public void loadCircleImage(SimpleDraweeView view, String url) {
        if(view != null && UtilString.isNotBlank(url)) {
            view.setHierarchy(mCircleHierarchyBuilder.build());
            Uri uri = Uri.parse(url);
            view.setImageURI(uri);
        }
    }

    /**
     *
     * @param view
     * @param gifRes
     */
    public void loadGifRes(SimpleDraweeView view, int gifRes) {
        if(view != null && gifRes>0) {
            Uri uri = Uri.parse(CstScheme.RES+ CstOuer.PACKAGE_NAME + "/" + gifRes);
             DraweeController controller = Fresco.newDraweeControllerBuilder()
                        .setUri(uri)
                        .setAutoPlayAnimations(true)
                        .build();
            view.setController(controller);
        }

    }


    /**
     * 加载水平倾斜图片
     * @param view
     * @param url
     */
    public void loadSkewXImage(SimpleDraweeView view, String url) {
        if(view != null) {
            ImageRequest request = ImageRequestBuilder.newBuilderWithSource(Uri.parse(url))
                    .setPostprocessor(mSkewXPostprocessor)
                    .build();

            PipelineDraweeController controller = (PipelineDraweeController)
                    Fresco.newDraweeControllerBuilder()
                            .setImageRequest(request)
                            .setOldController(view.getController())
                            .build();
            view.setController(controller);
        }
    }
}
